package com.hubu.exceptions;

import com.hubu.result.R;
import org.springframework.stereotype.Component;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * @Author xiedi
 * @Date: 2022/10/18
 */
@RestControllerAdvice
@Component
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public R error(Exception e) {
        e.printStackTrace();
        return R.error().message("服务器异常");
    }
    @ExceptionHandler(SQLException.class)
    public R error(SQLIntegrityConstraintViolationException e) {
        e.printStackTrace();
        return R.error().message("亲，用户名已存在！！！");
    }

    @ExceptionHandler(KgException.class)
    public R error(KgException e) {
        e.printStackTrace();
        return R.error().message(e.getMsg());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public String methodArgumentNotValidException(MethodArgumentNotValidException e){
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        StringBuffer sb = new StringBuffer();
        for (FieldError fieldError : fieldErrors) {
            String defaultMessage = fieldError.getDefaultMessage();
            sb.append(defaultMessage).append(",");
        }
        return sb.toString();
    }
}
